﻿#include "httpserver.h"

HttpServer::HttpServer(QObject *parent)
    : QObject{parent}
{
    mQTcpServer = new QTcpServer(this);

    mQHttpServer.bind(mQTcpServer);
    // test code
    // mQHttpServer.listen(QHostAddress::Any, 8081);


    mQHttpServer.route("/<arg>/<arg>", QHttpServerRequest::Method::Get, [this] (QString name, QString state, QHttpServerResponder &&responder, const QHttpServerRequest &request) {
        log(tr("HTTP remoteAddress:%1 remotePort:%2 name:%3 state:%4").arg(request.remoteAddress().toString(), QString(request.remotePort()), name, state));
        (void)request;
        emit requestInd(name, state);
        responder.write("OK", "text/plain");
    });
    log(QString("HttpServer Created."));
}

HttpServer::~HttpServer()
{
    if (mQTcpServer != nullptr) {
        delete mQTcpServer;
        mQTcpServer = nullptr;
    }
}

HttpServer *HttpServer::getInstance()
{
    static HttpServer *myHttpServer = new HttpServer();
    return myHttpServer;
}

int HttpServer::start(int port)
{
    if (mQTcpServer->isListening()) {
        qDebug("Tcp Server is listening, change to closed");
        mQTcpServer->close();
    }
    if (!mQTcpServer->listen(QHostAddress::Any, port)) {
        log("listening error, reason: " + mQTcpServer->errorString());
        return -1;
    } else {
        log(QString("Listening Port %1 succeed").arg(mQTcpServer->serverPort()));
    }
    return 0;
}

int HttpServer::stop()
{
    if (!mQTcpServer->isListening()) {
        qDebug("Tcp Server not listening");
        return -1;
    }
    mQTcpServer->close();
    log("TcpServer closed");
    return 0;
}

void HttpServer::log(QString s)
{
    QString logs = "[HttpServer]: " + s;
    emit logsPrintSignal(logs);
    qDebug() << logs;
}
